package com.lis.scf.security;

import com.alibaba.fastjson.JSON;
//import com.enterprise.common.enums.BusinessExceptionEnum;
//import com.enterprise.dto.ResponseDTO;
import com.lis.scf.common.dto.ResponseDTO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 认证失败处理器（未登录或令牌无效时触发）
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException authException
    ) throws IOException {
        // 设置响应格式为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 设置状态码为401（未认证）
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        // 构建错误响应
        ResponseDTO<Void> errorResponse = ResponseDTO.fail(
                10301,
                "令牌无效或已过期：" + authException.getMessage()
        );

        // 写入响应
        response.getWriter().write(JSON.toJSONString(errorResponse));
    }
}
